﻿using System;
using System.ServiceModel.Syndication;
using NCMIS.ObjectModel;
using NCMIS.ServiceModel.Syndication;

namespace NCMIS.Client
{
    public class CmisFolder
    {
        /// <summary>
        /// Creates a cmis:folder instance at the targeted CMIS service.
        /// </summary>
        /// <param name="webRequest">The web request to use.</param>
        /// <param name="name">The name of the folder to create.</param>
        /// <param name="childrenFeedUri">The children feed, where to create the folder.</param>
        /// <returns>A <see cref="System.ServiceModel.Syndication.SyndicationItem"/> object holding the folder instance.</returns>
        public static SyndicationItem CreateFolder(CmisWebRequest webRequest, string name, Uri childrenFeedUri)
        {
            SyndicationItem folderEntry = CreateFolderEntry(name);
            folderEntry = webRequest.InvokeSyndicationFeed(childrenFeedUri.AbsoluteUri, folderEntry);
            return folderEntry;
        }

        /// <summary>
        /// Creates a folder entry.
        /// </summary>
        /// <param name="name">The name of the folder to create.</param>
        /// <returns>A <see cref="System.ServiceModel.Syndication.SyndicationItem"/> object holding the folder instance.</returns>
        private static SyndicationItem CreateFolderEntry(string name)
        {
            CmisObject cmisObject = CreateCmisObject(name);

            CmisSyndicationItem entry = new CmisSyndicationItem()
            {
                Id = String.Format("urn:uuid:{0}-object", name),
                Title = new TextSyndicationContent(name),
                LastUpdatedTime = new DateTimeOffset(DateTime.Now),
                PublishDate = new DateTimeOffset(DateTime.Now)
            };

            entry.Authors.Add(new SyndicationPerson() { Name = "Administrator" });
            entry.AddObject(cmisObject);
            return entry;
        }

        /// <summary>
        /// Creates a CMIS folder object.
        /// </summary>
        /// <param name="name">the name of the folder to create.</param>
        /// <returns>A <see cref="NCMIS.ObjectModel.CmisObject"/> object holding the folder instance.</returns>
        private static CmisObject CreateCmisObject(string name)
        {
            CmisObject cmisObject = new CmisObject();
            CmisProperties properties = new CmisProperties()
            {
                Items = new CmisProperty[]
                {
                    //PropertyFactory.CreateObjectId(name),     // Commented since Alfresco doesn't accept this entry
                    PropertyFactory.CreateBaseTypeId("cmis:folder"),
                    PropertyFactory.CreateObjectTypeId("cmis:folder"),
                    PropertyFactory.CreateName(name)
                }
            };
            cmisObject.Properties = properties;
            return cmisObject;
        }
    }
}
